package cn.kailangtu.dataspot.tasks;

import android.os.SystemClock;
import android.util.Log;

import cn.kailangtu.commontools.AppVariable;
import cn.kailangtu.dataspot.data.HighData;
import cn.kailangtu.serialutils.api.Com2;
import cn.kailangtu.serialutils.api.ReceiveMsgListenerV2;
import cn.kailangtu.serialutils.api.SerialPortApi;
import cn.kailangtu.serialutils.modbus.modbusUtil;

public class HongWaiTask extends BaseTask {

    @Override
    void init() {

        initCommand();
        initReceive();
        initSend();
    }

    @Override
    void close() {
        isRun = false;
        Com2.getInstance().close();
    }

    private void initCommand() {
        byte[] cmd1 = modbusUtil.read(1, new byte[]{0x00, (byte) 0x0C}, new byte[]{0x00, 0x23});
        lsReadCom.add(cmd1);

    }


    private void initReceive() {
        if (AppVariable.platform_version == 450) {
            Com2.getInstance().openSerialPort485(new ReceiveMsgListenerV2() {
                @Override
                public void onReceiveData(byte[] data) {
                    //  Loggers.errInfo("COM1来了：");
                    receiveTime = System.currentTimeMillis();
                    Log.e("DiffTime,COM2", (receiveTime - sendTime) + "ms");
                    // Log.d("SEND AND RECEIVE","RECEIVE:PROCESS,BEGIN");
                    HighData.getInstance().readNewData(data);
                    // Log.d("SEND AND RECEIVE","RECEIVE:PROCESS,END");
                    isWaitReadCom = false;
                }
            });
        }
    }

    private void initSend() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
                while (isRun) {
                    if (SerialPortApi.getInstance().isOpen()) {
                        SystemClock.sleep(5);
                        if (!isWaitReadCom) {
                            isWaitReadCom = true;
                            isWaitReadIndexCom = 0;
                            sendTime = System.currentTimeMillis();
                            Com2.getInstance().sendData(lsReadCom.get(indexCom));
                        } else {
                            isWaitReadIndexCom++;
                            if (isWaitReadIndexCom > 200) {
                                isWaitReadCom = false;
                                Log.e("NEWNEWNEW", "COM2超时：" + (System.currentTimeMillis() - sendTime));
                            }
                        }
                    } else {
                        Log.d("COMCOM", "串口不通。");
                        SystemClock.sleep(1000);
                    }
                }
            }
        }).start();
    }
}
